<template>
  <el-row>
    <el-row>
      <div id="iframe" style="position: fixed;left: 30%;z-index: 100;" />
      <button id="xs_msisdn" style="display: none">{{ $t('collectDetail.dialNumber') }}</button>
    </el-row>
    <el-container>
      <el-main>
        <el-tabs type="border-card">
          <el-tab-pane :label="$t('authModule.reviewInfo')">
            <review-info
              :order-info-data="orderInfoData"
              :user-contact-data="userContactData"
              :user-info-data="userInfoData"
              @set-contact-state="setContactState"
            />
          </el-tab-pane>
          <el-tab-pane :label="$t('authModule.loanOrder')">
            <loan-order />
          </el-tab-pane>
          <el-tab-pane :label="$t('authModule.addressBook')">
            <address-book
              :phone-data="phoneData"
              @set-contact-state="setContactState"
            />
          </el-tab-pane>
          <el-tab-pane :label="$t('authModule.tripartite')">
            <tripartite />
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-aside v-if="staffData && staffData['recallPhone'] && staffData['recallPhonePassword']" width="200px">
        <el-card style="width: 200px;position: fixed">
          <h3>
            {{ userInfoData && userInfoData['phoneNumber'] ? userInfoData['phoneNumber'] : '' }}
          </h3>
          <el-row>
            <el-button
              type="primary"
              @click="phoneFn('isPhone')"
            >
              {{ $t('collectDetail.dial') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-button
              type="primary"
              @click="phoneFn('isSms')"
            >
              {{ $t('collectDetail.sendMessage') }}
            </el-button>
          </el-row>
        </el-card>
      </el-aside>
    </el-container>

    <el-row style="text-align: center;margin-bottom: 20px">
      <el-button
        v-if="para['from'] === 'riskList' && orderInfoData['status'] === 9 && orderInfoData['currentStageId'] === stageId"
        type="primary"
        :loading="passLoading"
        @click="passSubmit"
      >
        {{ $t('orderList.allList.opera.pass') }}
      </el-button>
      <el-button
        v-if="para['from'] === 'riskList' && orderInfoData['status'] === 9 && orderInfoData['currentStageId'] === stageId"
        type="primary"
        :loading="refuseLoading"
        @click="refuseSubmit"
      >
        {{ $t('orderList.allList.opera.refuse') }}
      </el-button>
      <el-button
        v-if="para['from'] === 'riskList' && orderInfoData['status'] === 9"
        type="primary"
        :loading="closeLoading"
        @click="closeSubmit"
      >
        {{ $t('orderList.allList.opera.close') }}
      </el-button>
      <el-button
        v-if="blackList && personalInfo['creditStatus'] !== 2"
        type="primary"
        :loading="addLoading"
        @click="addSubmit"
      >
        {{ $t('orderList.allList.opera.addBlacklist') }}
      </el-button>
      <el-button
        v-if="blackList && personalInfo['creditStatus'] === 2"
        type="primary"
        :loading="removeLoading"
        @click="removeSubmit"
      >
        {{ $t('orderList.allList.opera.removeBlacklist') }}
      </el-button>
    </el-row>
    <close-dialog :show-dialog="isClose" @change-dialog="changeDialog" @edit-success="editSuccess" />
    <pass-dialog :show-dialog="isPass" @change-dialog="changeDialog" @edit-success="editSuccess" />
    <refuse-dialog :show-dialog="isRefuse" :reject-desc-data="rejectDescData" @change-dialog="changeDialog" @edit-success="editSuccess" />
    <phone-dialog :show-dialog="isPhone" :staff-data="staffData" :user-contact-data="userContactData" :phone-data="phoneData" @change-dialog="changeDialog" @set-contact-state="setContactState" @call-phone="callPhone" />
    <sms-dialog :show-dialog="isSms" :staff-data="staffData" :user-contact-data="userContactData" :phone-data="phoneData" @change-dialog="changeDialog" @set-contact-state="setContactState" />
  </el-row>
</template>

<script>
import { orderInfo, personalInfo, userContact, updateUserContactStatusput, creditStatus, userInfo } from '@/api/auth'
import { getCurrentCreditAuditStaff, queryAuditRejectDesc, getCurrentStaffId } from '@/api/risk'
import CloseDialog from '@/components/risk/auth/close-dialog'
import PassDialog from '@/components/risk/auth/pass-dialog'
import RefuseDialog from '@/components/risk/auth/refuse-dialog'
import PhoneDialog from '@/components/risk/auth/phone-dialog'
import SmsDialog from '@/components/risk/auth/sms-dialog'
import ReviewInfo from '@/components/auth/reviewInfo'
import LoanOrder from '@/components/auth/loanOrder'
import AddressBook from '@/components/auth/addressBook'
import Tripartite from '@/components/auth/tripartite'
export default {
  name: 'Auth',
  components: {
    ReviewInfo,
    LoanOrder,
    AddressBook,
    Tripartite,
    CloseDialog,
    PassDialog,
    RefuseDialog,
    PhoneDialog,
    SmsDialog
  },
  data() {
    return {
      passLoading: false,
      refuseLoading: false,
      closeLoading: false,
      addLoading: false,
      removeLoading: false,
      isPass: false,
      isRefuse: false,
      isClose: false,
      isPhone: false,
      isSms: false,
      para: {},
      orderInfoData: {},
      userInfoData: {},
      staffData: {},
      personalInfo: {},
      stageId: null,
      rejectDescData: [],
      blackList: false,
      userContactData: [],
      phoneData: []
    }
  },
  mounted() {
    this.para = this.$route.query
    this.getData()
    this.getOrderInfo()
    this.getUserInfo()
    this.getPersonalInfo()
    this.getStaffId()
    this.getUserContact()
  },
  methods: {
    getData() {
      const loginInfo = JSON.parse(sessionStorage.getItem('loginInfo'))
      const blacklist = loginInfo['roleOutputBOS'].filter(v => {
        return v.id === 1 || v.id === 16
      })
      this.blackList = blacklist && blacklist.length > 0
      const loginInfoId = loginInfo.id
      if (this.para['from'] === 'riskList' && loginInfoId !== 1) {
        getCurrentCreditAuditStaff()
          .then(res => {
            if (res.success) {
              this.stageId = res.data['stageId']
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.$message.error(err.message)
          })
      }
    },
    getOrderInfo() {
      orderInfo(this.para['orderId'])
        .then(res => {
          if (res.success) {
            this.orderInfoData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getUserInfo() {
      userInfo(this.para['orderId'])
        .then(res => {
          if (res.success) {
            this.userInfoData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getPersonalInfo() {
      personalInfo(this.para['userId'])
        .then(res => {
          if (res.success) {
            this.personalInfo = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getStaffId() {
      getCurrentStaffId()
        .then(res => {
          if (res.success) {
            this.staffData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getUserContact() {
      userContact(this.para.orderId)
        .then(res => {
          if (res.success) {
            this.userContactData = res.data.filter(v => {
              return v['contactGrade'] > 0
            })
            this.phoneData = res.data.sort((a, b) => {
              return a['contactName'].localeCompare(b['contactName'])
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    setContactState(item, index) {
      const data = {
        id: item['id'],
        phoneNumStatus: index
      }
      updateUserContactStatusput(data)
        .then(res => {
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getUserContact()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    changeDialog(data, state) {
      this[data] = state
    },
    editSuccess() {
      setTimeout(() => {
        window.opener = null
        window.open('', '_self')
        window.close()
      }, 10)
    },
    passSubmit() {
      this.passLoading = true
      this.isPass = true
      this.passLoading = false
    },
    refuseSubmit() {
      this.refuseLoading = true
      queryAuditRejectDesc()
        .then(res => {
          if (res.success) {
            this.rejectDescData = res.data
            this.isRefuse = true
            this.refuseLoading = false
          } else {
            this.refuseLoading = false
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.refuseLoading = false
          this.$message.error(err.message)
        })
    },
    closeSubmit() {
      this.closeLoading = true
      this.isClose = true
      this.closeLoading = false
    },
    addSubmit() {
      this.addLoading = true
      const data = {
        id: this.para.userId,
        creditStatus: 2
      }
      creditStatus(data)
        .then(res => {
          this.addLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getPersonalInfo()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    removeSubmit() {
      this.removeLoading = true
      const data = {
        id: this.para.userId,
        creditStatus: 0
      }
      creditStatus(data)
        .then(res => {
          this.removeLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getPersonalInfo()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    phoneFn(data) {
      this[data] = true
    },
    callPhone(data) {
      const account = 'EasyKlick'
      const password = 'b99846c549c57aa213fa8fe0033afdea' // 后台密码MD5
      const channelKey = 'f323ea1ffd5b4cf68a4e7d4f959955a7' // 后台channelKey
      // const voipAccount = '827404001'
      // const voipPassword = '29884818' // VOIP密码
      const voipAccount = this.staffData['recallPhone']
      const voipPassword = this.staffData['recallPhonePassword'] // VOIP密码
      const msisdn = data // 手机号，请使用0开头格式
      console.log(data)
      const extendId = 'xs_' + this.para.orderId // 自定义的唯一扩展ID-需要绑定此通会话的id，此字段由客户提供，用于将通话记录关联进客户的通话记录中
      // 需要回调响应的Url，需要进行URL编码，格式为：http://xxxxx/xxx?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}
      // let postUrl = encodeURI('https://newback.kilatkre.top/urgentRecall/webcall/callback?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}' )
      const postUrl = encodeURI(`${process.env.VUE_APP_BASE_API}/urgentRecall/webcall/callback?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}`)
      window.STI.call('xs_msisdn', 'iframe', account, password, channelKey, voipAccount, voipPassword, msisdn, extendId, postUrl)
      this.isPhone = false
      this.call()
    },
    call() {
      $('#xs_msisdn').click()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-main{
  padding: 10px;
}
.el-aside{
  background-color: white;
  padding: 0;
  margin: 10px;
  .el-card .el-button{
    width: 100%;
  }
}
</style>
